import htmlentitydefs, re
from BeautifulSoup import BeautifulSoup, Comment

from django.template.defaultfilters import stringfilter
from google.appengine.ext import webapp
register = webapp.template.create_template_register()


def sanitize(value, valid_tags_arg = 'p i strong b u h1 h2 h3 pre br'):
    """
    Idea taken from: http://www.djangosnippets.org/snippets/205/
    """
    valid_tags = valid_tags_arg.split()
    valid_attrs = 'href src'.split()
    soup = BeautifulSoup(value)
    for comment in soup.findAll(
        text=lambda text: isinstance(text, Comment)):
        comment.extract()
    for tag in soup.findAll(True):
        if tag.name not in valid_tags:
            tag.hidden = True
        tag.attrs = [(attr, val) for attr, val in tag.attrs
                     if attr in valid_attrs]
    return soup.renderContents().decode('utf8').replace('javascript:', '')

register.filter(sanitize)


def slugfy(value, separator = '-'):
  ret = ""
  for c in value.lower():
    try:
      ret += htmlentitydefs.codepoint2name[ord(c)]
    except:
      ret += c
      ret = re.sub("([a-zA-Z])(uml|acute|grave|circ|tilde|cedil)", r"\1", ret)
      ret = re.sub("\W", " ", ret)
      ret = re.sub(" +", separator, ret)
  ret = ret.strip()
  if ret[0] == separator:
    ret = ret[1:]
  return ret

register.filter(slugfy)
